<template>
  <div class="monthly-summary">
    <div class="page-header">
      <h2>月度考勤汇总</h2>
    </div>
    
    <!-- 搜索和操作区域 -->
    <div class="search-section">
      <el-form :model="searchForm" inline size="default">
        <el-form-item label="年月:">
          <el-date-picker
            v-model="searchForm.yearMonth"
            type="month"
            placeholder="2025-01"
            format="YYYY-MM"
            value-format="YYYY-MM"
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="单位名称:">
          <el-input
            v-model="searchForm.teamName"
            placeholder="请输入单位名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">确认检索</el-button>
        </el-form-item>
      </el-form>
      
      <div class="action-buttons">
        <el-button @click="handleReset">重置</el-button>
        <el-button @click="handleCalculate">重算</el-button>
        <el-button type="success" @click="handleExport">导出</el-button>
      </div>
    </div>
    
    <!-- 汇总表格 -->
    <div class="summary-section">
      <el-table
        :data="tableData"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column prop="序号" label="序号" width="80" align="center" />
        <el-table-column prop="teamName" label="单位名称" width="200" />
        <el-table-column prop="totalEmployees" label="总人数" width="100" align="center" />
        <el-table-column prop="whiteShiftDays" label="白班天数" width="120" align="center" />
        <el-table-column prop="nightShiftDays" label="夜班天数" width="120" align="center" />
        <el-table-column prop="absent1To5Days" label="缺勤人数1-5天" width="120" align="center" />
        <el-table-column prop="absent5To10Days" label="缺勤人数5-10天" width="120" align="center" />
        <el-table-column prop="absentOver10Days" label="缺勤人数≥10天" width="120" align="center" />
        <el-table-column prop="attendanceRate" label="出勤率" width="100" align="center">
          <template #default="{ row }">
            <span :class="getAttendanceRateClass(row.attendanceRate)">
              {{ row.attendanceRate }}%
            </span>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <span class="total-text">共{{ total }}条记录</span>
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="prev, pager, next, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getMonthlyAttendanceSummaryByTeam, exportMonthlySummaryReport } from '@/api/attendance'
import dayjs from 'dayjs'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)

const searchForm = reactive({
  yearMonth: dayjs().format('YYYY-MM'),
  teamName: ''
})

const pagination = reactive({
  pageNum: 1,
  pageSize: 10
})

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      yearMonth: searchForm.yearMonth,
      teamName: searchForm.teamName || undefined
    }
    
    const res = await getMonthlyAttendanceSummaryByTeam(params)
    const data = res.data
    
    tableData.value = data.records?.map((item, index) => ({
      ...item,
      序号: (pagination.pageNum - 1) * pagination.pageSize + index + 1,
      // 计算出勤率：基于缺勤情况计算
      attendanceRate: item.totalEmployees > 0 ? 
        ((item.totalEmployees - (item.absentOver10Days || 0) - (item.absent5To10Days || 0) - (item.absent1To5Days || 0)) / item.totalEmployees * 100).toFixed(1)
        : '0.0'
    })) || []
    
    total.value = data.total || 0
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageNum = 1
  loadData()
}

const handleReset = () => {
  searchForm.yearMonth = dayjs().format('YYYY-MM')
  searchForm.teamName = ''
  pagination.pageNum = 1
  loadData()
}

const handleCalculate = () => {
  ElMessage.info('重算功能待实现')
}

const handleExport = async () => {
  try {
    const params = {
      yearMonth: searchForm.yearMonth,
      teamName: searchForm.teamName || undefined
    }
    
    const res = await exportMonthlySummaryReport(params)
    
    // 创建下载链接
    const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `月度考勤汇总_${searchForm.yearMonth}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
  }
}

const handleSizeChange = (val) => {
  pagination.pageSize = val
  pagination.pageNum = 1
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.pageNum = val
  loadData()
}

const getAttendanceRateClass = (rate) => {
  if (rate >= 95) return 'excellent'
  if (rate >= 90) return 'good'
  if (rate >= 80) return 'normal'
  return 'poor'
}

const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    
    if (index === 1) {
      sums[index] = ''
      return
    }
    
    const values = data.map(item => Number(item[column.property]))
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
      
      if (column.property === 'attendanceRate') {
        sums[index] = (sums[index] / data.length).toFixed(1) + '%'
      }
    } else {
      sums[index] = ''
    }
  })
  
  return sums
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.monthly-summary {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      color: #333;
      margin: 0;
    }
  }
  
  .search-section {
    background: #f8f9fa;
    padding: 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    
    .action-buttons {
      display: flex;
      gap: 10px;
      
      .el-button {
        min-width: 80px;
      }
    }
  }
  
  .summary-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
    
    .el-table {
      flex: 1;
    }
    
    .pagination-section {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 20px;
      padding-top: 20px;
      border-top: 1px solid #ebeef5;
      
      .total-text {
        color: #666;
        font-size: 14px;
      }
    }
  }
}

.excellent {
  color: #52c41a;
  font-weight: bold;
}

.good {
  color: #1890ff;
  font-weight: bold;
}

.normal {
  color: #fa8c16;
}

.poor {
  color: #ff4d4f;
  font-weight: bold;
}

// 表格样式优化
:deep(.el-table) {
  .el-table__header-wrapper {
    th {
      background-color: #f5f7fa;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .el-table__row {
    &:hover {
      background-color: #f5f7fa;
    }
  }
}
</style>